import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import StuSystem from '../views/StuSystem.vue'
import StuList from '@/components/student/stuList/StuList.vue'
import api from '@/http/api/apis'
import Element from 'element-ui'

let v = new Vue();

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/stuSystem'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/stuSystem',
    component: StuSystem,
    children: [
      // 学生相关-------------------
      {
        path: '',
        component: StuList,
        meta: {
          keepAlive: false
        },
      },
      {
        path: 'addStu',
        component: () => import('@/components/student/addStu/AddStu.vue'),
        meta: {
          keepAlive: false
        },
      },
      {
        path: 'updateStu/:id',
        props: true,
        component: () => import('@/components/student/updateStu/UpdateStu.vue'),
        meta: {
          keepAlive: false
        },
      },
      // 班级相关-------------------
      {
        path: 'classList',
        component: () => import('@/components/class/ClassList.vue'),
        meta: {
          keepAlive: false
        },
      },
      {
        path: 'addClass',
        component: () => import('@/components/class/AddClass.vue'),
        meta: {
          keepAlive: false
        },
      },
      //教师相关-------------------
      {
        path: 'teacherList',
        component: () => import('@/components/teacher/TeacherList.vue'),
        meta: {
          keepAlive: false
        },
      },
      {
        path: 'addTeacher',
        component: () => import('@/components/teacher/AddTeacher.vue'),
        meta: {
          keepAlive: true
        },
      },
      //其他
      {
        path: 'other',
        component: () => import('@/components/Other.vue'),
        meta: {
          keepAlive: true
        },
      },
    ]
  }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})


//路由白名单
const whiteList = ['/login', '/register']

//全局路由守卫--验证token -用户登录状态
router.beforeEach(
  async (to, from, next) => {
    console.log(to.path);
    //检索白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      const { data } = await api.loginApi.isLogin();
      console.log(data);
      //验证成功
      if (data.status) {
        //本地储存用户姓名 供调用、
        //使用了 btoa 加密 可以使用atob解密
        localStorage.username = btoa(data.data.username)

        next()
      } else {
        v.$notify.error({
          title: '未登录，请到登录页登录',
          message: data.message
        })
        next('/login')
      }
    }

  }
)

export default router
